<?php
/**
 * @name 产品控制器
 * @Author : yu
 * @Created : 2016-10-28
 * @Copyright : MPE.Fiidee.Monda.Cn
 */
namespace admin\action;

use herosphp\core\Loader;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use models\ProductModel;
use utils\x1\MyNumber;


class ProductAction extends CommonAction
{

    public function C_start()
    {
        $this->assign("pro_unit",C("pro_unit"));
        $this->assign("pro_std",C("pro_std"));
        parent::C_start();
    }

    protected $serviceBean = "product.product.service";
    protected $order = array('edittime' => -1);

    public function indexBySale(HttpRequest $request)
    {
        $productService = Beans::get($this->serviceBean);

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page = $page;
        $this->pagesize = $pagesize;

        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
			"select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "delivery_way" => $request->getParameter('delivery_way'),
        );

        $search_arr['status'] = ProductModel::STATUS_ON_SHELF;

        if ($request->getParameter('export') == 1) {
            $page = 1;
            $pagesize = 2147483648;
            $ids = $request->getParameter('ids');
            if ($ids) {
                $tmp = "('0'";
                foreach ($ids as $value) {
                    $tmp .= ',' . "'$value'";
                }
                $search_arr['id'] = $tmp . ')';
            }
        }

        $arr = $productService->searchBySaleAndStore($pagesize, $page, $search_arr);

        $items = $arr['items'];

        $itemsLen = count($items);

        for ($i = 0; $i < $itemsLen; $i++) {

            $items[$i]['delivery_way'] = $productService->getDeliveryWayText($items[$i]['delivery_way']);
            $items[$i]['publish_way'] = $productService->getPublishWayText($items[$i]['publish_way']);
            $items[$i]['status'] = $productService->getStatusText($items[$i]['status']);
            //if $value[quantity]==0||($value[quantity]-$value[freeze_quantity])==0

            $items[$i]['quantity'] = bcsub($items[$i]['quantity'], $items[$i]['freeze_quantity'], 3);

        }
        //var_dump($items);
        if ($request->getParameter('export') == 1) {
            $excel = array();
            foreach ($items as $k => $v) {
                $tmp = array();
                $tmp[] = $v["product_no"];
                $tmp[] = $v["type_name"];
                $tmp[] = $v["product_name"];
                $tmp[] = $v["factory_name"];
                $tmp[] = $v["brand_name"];
                $tmp[] = $v["min_volume"];
                $tmp[] = $v["quantity"];
                $tmp[] = $v["freeze_quantity"];
                $tmp[] = $v["sales_price"];
                $tmp[] = $v["cost_price"];
                $tmp[] = $v["pkg_size"];
                $tmp[] = $v["delivery_way"];
                $tmp[] = $v["status"];
                $tmp[] = $v["repertory_name"];
                $excel[] = $tmp;
            }
            $header = array('产品货号', '分类', '品名', '厂家', '牌号',"最小交易量(吨)", '数量(吨)', '冻结数量(吨)','销售价(元/吨)', '成本价(元/吨)', '货品规格(KG/袋)', '交收方式', '状态','仓库');
            phpexcel("出售中的商品", $header, $excel);
            exit();
        }

        $this->generatePageMenu($arr['total']);

        $this->assign('items', $items);
        $this->assign('search_arr', $search_arr);

        $this->setView('/product/indexBySale');

        $this->assign("title", "出售中的商品");
        $this->assign('bread', array('商品管理', $this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
    }

    public function indexByStore(HttpRequest $request)
    {
        $productService = Beans::get($this->serviceBean);

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page = $page;
        $this->pagesize = $pagesize;

        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "delivery_way" => $request->getParameter('delivery_way'),

        );

        $search_arr['status'] = ProductModel::STATUS_OFF_SHELF;

        if ($request->getParameter('export') == 1) {
            $pagesize = 99999;
            $ids = $request->getParameter('ids');
            if ($ids) {
                $tmp = "('0'";
                foreach ($ids as $value) {
                    $tmp .= ',' . "'$value'";
                }
                $search_arr['id'] = $tmp . ')';
            }
        }

        $arr = $productService->searchBySaleAndStore($pagesize, $page, $search_arr);

        $items = $arr['items'];

        $itemsLen = count($items);

        for ($i = 0; $i < $itemsLen; $i++) {

            $items[$i]['delivery_way'] = $productService->getDeliveryWayText($items[$i]['delivery_way']);
            $items[$i]['publish_way'] = $productService->getPublishWayText($items[$i]['publish_way']);
            $items[$i]['status'] = $productService->getStatusText($items[$i]['status']);
            $items[$i]['quantity'] = bcsub($items[$i]['quantity'], $items[$i]['freeze_quantity'], 3);

        }

        if ($request->getParameter('export') == 1) {
            $excel = array();
            foreach ($items as $k => $v) {
                $tmp = array();
                $tmp[] = $v["product_no"];
                $tmp[] = $v["type_name"];
                $tmp[] = $v["product_name"];
                $tmp[] = $v["factory_name"];
                $tmp[] = $v["brand_name"];
                $tmp[] = $v["min_volume"];
                $tmp[] = $v["quantity"];
                $tmp[] = $v["freeze_quantity"];
                $tmp[] = $v["sales_price"];
                $tmp[] = $v["cost_price"];
                $tmp[] = $v["pkg_size"];
                $tmp[] = $v["delivery_way"];
                $tmp[] = $v["status"];
                $tmp[] = $v["repertory_name"];
                $excel[] = $tmp;
            }
            //$header = array('产品货号', '分类', '品名', '厂家', '牌号', '数量(吨)', '销售价(元/吨)', '成本价(元/吨)', '货品规格(KG/袋)', '交收方式', '状态');
            $header = array('产品货号', '分类', '品名', '厂家', '牌号', "最小交易量(吨)",'数量(吨)', '冻结数量(吨)','销售价(元/吨)', '成本价(元/吨)', '货品规格(KG/袋)', '交收方式', '状态','仓库');
            phpexcel("仓库中的商品", $header, $excel);
            exit();
        }

        $this->generatePageMenu($arr['total']);

        $this->assign('from', $request->getMethod());

        $this->assign('items', $items);
        $this->assign('search_arr', $search_arr);
        $this->setView('/product/indexByStore');

        $this->assign("title", "仓库中的商品");
        $this->assign('bread', array('商品管理', $this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
    }

    public function searchProductList(HttpRequest $request)
    {

        $productService = Beans::get($this->serviceBean);
        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');
        $member_id = $request->getParameter('member_id');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page = $page;
        $this->pagesize = $pagesize;


        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),

        );
        //$search_arr['status'] = ProductModel::STATUS_ON_SHELF;

        $arr = $productService->searchBySaleAndStore($pagesize, $page, $search_arr);

        $items = $arr['items'];

        $itemsLen = count($items);

        for ($i = 0; $i < $itemsLen; $i++) {

            $items[$i]['delivery_way'] = $productService->getDeliveryWayText($items[$i]['delivery_way']);
            $items[$i]['publish_way'] = $productService->getPublishWayText($items[$i]['publish_way']);
            $items[$i]['status'] = $productService->getStatusText($items[$i]['status']);
            $items[$i]['orgin_sales_price'] = $items[$i]['sales_price'];

            if ($member_id != '') {

                $productMember = $productService->getProductMember($items[$i]['id'], $member_id);

                if ($productMember) {

                    $items[$i]['sales_price'] = $productMember['sales_price'];
                    $items[$i]['member_sales_price'] = $productMember['sales_price'];

                } else {
                    $items[$i]['sales_price'] = $items[$i]['orgin_sales_price'];

                }

            }

        }


        $this->generatePageMenu($arr['total']);

        $this->assign('items', $items);
        $this->assign('search_arr', $search_arr);
        $this->assign('member_id', $member_id);

        $this->setView('/product/productList');

        $this->assign("title", "商品库");
        $this->assign('bread', array('商品管理', $this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));


    }

    public function add(HttpRequest $request)
    {
        $productService = Beans::get($this->serviceBean);
        $repertoryService = Beans::get('repertory.repertory.service');

        $this->assign("groupMembers", $productService->getGroupMembers());
        $this->assign("repertoryList", $repertoryService->getRepertorys());

        parent::add($request);

        $this->assign("title", "商品发布");
        $this->assign('bread', array('商品管理', $this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));

    }

    public function edit(HttpRequest $request)
    {
        $productService = Beans::get($this->serviceBean);
        $repertoryService = Beans::get('repertory.repertory.service');

        $id = $request->getParameter('id');
        $from = $request->getParameter('from');

        $item = $productService->getProduct2($id);

        $publish_way_is_members = $productService->getPublishWayIsMembers($id);

        $this->assign("from", $from);

        $this->assign("id", $id);
        $this->assign("item", $item);
        $this->assign("repertoryList", $repertoryService->getRepertorys());
        $this->assign("publish_way_is_members", join(',', $publish_way_is_members));

        $this->assign("groupMembers", $productService->getGroupMembers($publish_way_is_members));

        $deliveryWayList = $productService->getDeliveryWayText();
        $publishWayList = $productService->getPublishWayText();
        $valuationTypeList = $productService->getValuationTypeText();

        $this->assign("deliveryWayList", $deliveryWayList);
        $this->assign("publishWayList", $publishWayList);
        $this->assign("valuationTypeList", $valuationTypeList);


        $this->assign("title", "商品编辑");
        $this->assign('bread', array('商品管理','商品库',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/product/indexBySale'),'javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/edit');

    }

    //上架
    public function do_onShelf(HttpRequest $request)
    {

        $productService = Beans::get($this->serviceBean);

        $ids = $request->getParameter('ids');

        if (empty($ids)) AjaxResult::ajaxResult('error', COM_ERR_MSG);
        if (!is_array($ids)) {

            $ids = array($ids);
        }

        $productService->onShelf($ids) ? AjaxResult::ajaxResult(0, '上架成功') : AjaxResult::ajaxResult(1, '上架失败');

    }

    //下架
    public function do_offShelf(HttpRequest $request)
    {

        $productService = Beans::get($this->serviceBean);

        $ids = $request->getParameter('ids');

        if (empty($ids)) AjaxResult::ajaxResult('error', COM_ERR_MSG);

        if (!is_array($ids)) {

            $ids = array($ids);
        }
        $mesage='';
        foreach($ids as $k=>$v){

            if($row=$productService->validateProductInUnFinishedOrder($v)){
                $trans = array_flip($ids);
                unset($ids[$trans[$row['id']]]);
                $mesage.="商品:{$row['product_no']}在未完成订单{$row['order_no']}中，无法下架<br><br>";

            }
        }

        if(count($ids)>=1){

            $productService->offShelf($ids) ? AjaxResult::ajaxResult('000', '<h4 style="margin-top: 1px">下架成功</h4>'.$mesage) : AjaxResult::ajaxResult('001', '下架失败');


        }else{
            AjaxResult::ajaxResult('001', '<h4 style="margin-top: 1px">下架失败</h4>'.$mesage);

        }

    }

    //获取货号
    public function getProductNo(HttpRequest $request)
    {

        $data = $request->getParameters('data');
        $productNo = Beans::get($this->serviceBean)->getProductNo($data);

        echo $productNo ? json_encode(array('code' => 0, 'data' => $productNo)) : json_encode(array('code' => 1, 'data' => $productNo));

        die;
    }


    public function do_add(HttpRequest $request)
    {
        //$productModel = Loader::model('product');

        $data = $request->getParameter('data');

        $productService = Beans::get($this->serviceBean);

        if ($data['cost_price'] == '') {

            $data['cost_price'] = null;

        }
        if ($data['publish_way'] == 2 && $data['publish_way_is_members'] == '') {

            AjaxResult::ajaxResult('001', '选择“指定会员”发布方式，需指定会员');

        }
        if ($data['publish_way'] == 3 && $data['publish_way_is_members'] == '') {

            AjaxResult::ajaxResult('001', '选择“公开和指定会员”发布方式，需指定会员');

        }
        if ($data['min_volume'] > $data['quantity']) {

            AjaxResult::ajaxResult('001', '最小交易量不能大于数量');

        }
        if ($productService->selectSameProduct($data['type_name'], $data['product_name'], $data['factory_name'], $data['brand_name'], $data['pkg_size'])) {

            AjaxResult::ajaxResult('001', '发布的商品已存在');

        }
        //die;
        $productService->add($data) ? AjaxResult::ajaxResult('000', '添加成功') : AjaxResult::ajaxResult('001', '添加失败');

    }

    public function do_edit(HttpRequest $request)
    {
        $data = $request->getParameter('data');
        $id = $request->getParameter('id');

        $productService = Beans::get($this->serviceBean);

        if ($productService->selectSameProduct($data['type_name'], $data['product_name'], $data['factory_name'], $data['brand_name'], $data['pkg_size'], $id)) {

            AjaxResult::ajaxResult('001', '发布的商品已存在');

        }

        if ($data['cost_price'] == '') {

            $data['cost_price'] = null;

        }
        if ($data['publish_way'] == 2 && $data['publish_way_is_members'] == '') {

            AjaxResult::ajaxResult('001', '选择“指定会员”发布方式，需指定会员');

        }
        if ($data['publish_way'] == 3 && $data['publish_way_is_members'] == '') {

            AjaxResult::ajaxResult('001', '选择“公开和指定会员”发布方式，需指定会员');

        }
        if (!$productService->validateQtyFromFreezeQty($data['quantity'], $id)) {

            AjaxResult::ajaxResult('001', '数量不能小于此时的冻结数量');

        }

        $productService->update($data, $id) ? AjaxResult::ajaxResult('000', '更新成功') : AjaxResult::ajaxResult('001', '更新失败');


    }

    /**
     * 删除单条数据
     * @param HttpRequest $request
     */
    public function delete(HttpRequest $request)
    {

        $productModel = Loader::model('product');

        $id = $request->getParameter('id');
        if ($id == "") AjaxResult::ajaxResult('error', COM_ERR_MSG);

        if ($productModel->update(array('is_delete' => 1), $id)) {

            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

}
